<template>
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        @close="handleClose"
        width="60%"
        v-dialogDrag
        append-to-body
    >
        <el-form
            ref="formRef"
            :model="formData"
            v-loading="formLoading"
            label-width="100px"
        >
            <el-row>
                <el-col :span="12">
                    <el-form-item
                        label="工单类型"
                        prop="workType"
                        :rules="[
                            {
                                required: true,
                                message: '请选择工单类型',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-select
                            v-model="formData.workType"
                            style="width: 100%"
                            filterable
                            placeholder="请选择工单类型"
                        >
                            <el-option
                                v-for="(item, index) in workTypeList"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item
                        label="工单名称"
                        prop="workName"
                        :rules="[
                            {
                                required: true,
                                message: '请输入工单名称',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-input
                            v-model="formData.workName"
                            placeholder="请输入工单名称"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" v-if="formData.workType === 1">
                    <el-form-item
                        label="工单链接"
                        prop="workUrl"
                        :rules="[
                            {
                                required: true,
                                validator: validateUrl,
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-input
                            v-model="formData.workUrl"
                            style="width: 100%"
                            placeholder="请输入工单链接"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item
                        label="分流链接"
                        prop="linkId"
                        :rules="[
                            {
                                required: true,
                                message: '请选择分流链接',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-select
                            v-model="formData.linkId"
                            style="width: 100%"
                            placeholder="请选择分流链接"
                            filterable
                        >
                            <el-option
                                v-for="(item, index) in linksData"
                                :key="index"
                                :label="`${item.linkUrl}${
                                    item.linkDescription
                                        ? `（${item.linkDescription}）`
                                        : ''
                                }`"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item
                        label="号码类型"
                        prop="numberType"
                        :rules="[
                            {
                                required: true,
                                message: '请选择号码类型',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-select
                            v-model="formData.numberType"
                            style="width: 100%"
                            placeholder="请选择号码类型"
                        >
                            <el-option
                                v-for="(item, index) in numberTypeList"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="formData.workType === 1">
                <el-col :span="12">
                    <el-form-item
                        label="开始时间"
                        prop="startTime"
                        :rules="[
                            {
                                required: true,
                                message: '请选择开始时间',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-date-picker
                            v-model="formData.startTime"
                            type="datetime"
                            placeholder="选择开始时间"
                            style="width: 100%"
                            format="yyyy-MM-dd HH:mm"
                            value-format="yyyy-MM-dd HH:mm"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item
                        label="到期时间"
                        prop="endTime"
                        :rules="[
                            {
                                required: true,
                                message: '请选择到期时间',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-date-picker
                            v-model="formData.endTime"
                            type="datetime"
                            placeholder="选择到期时间"
                            format="yyyy-MM-dd HH:mm"
                            value-format="yyyy-MM-dd HH:mm"
                            style="width: 100%"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="formData.workType === 1">
                <el-col :span="12">
                    <el-form-item
                        label="工单总量"
                        prop="workOrderTotal"
                        :rules="[
                            {
                                required: true,
                                message: '请输入工单总量',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-input
                            v-model="formData.workOrderTotal"
                            placeholder="请输入工单总量"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item
                        label="下号比例"
                        prop="lowerProportion"
                        :rules="[
                            {
                                required: true,
                                message: '请输入下号比例',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-input-number
                            v-model="formData.lowerProportion"
                            :min="1"
                            placeholder="请输入下号比例"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="formData.workType === 1">
                <el-col :span="12">
                    <el-form-item label="工单账号" prop="workAccount">
                        <el-input
                            v-model="formData.workAccount"
                            placeholder="请输入工单账号"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="工单密码" prop="workPassword">
                        <el-input
                            v-model="formData.workPassword"
                            placeholder="请输入工单密码"
                            type="password"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="flex">
                <el-form-item label="智能关单" prop="autoCloseEnabled">
                    <el-switch v-model="formData.autoCloseEnabled" />
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="完成比例>= 100%时,工单状态自动关闭！"
                        placement="top-start"
                    >
                        <i class="el-icon-warning" style="margin: 0 0 0 10px"></i>
                    </el-tooltip>
                </el-form-item>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button
                type="primary"
                @click="submitForm"
                :disabled="formLoading"
                >确 定</el-button
            >
            <el-button @click="dialogVisible = false">取 消</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { addWorkOrder, editWorkOrder } from "@/api/worksheet";
export default {
    props: {
        linksData: {
            type: Array,
            default: () => {
                return [];
            },
        },
    },
    data() {
        return {
            // 弹出层标题
            dialogTitle: "",
            // 是否显示弹出层,
            dialogVisible: false,
            formLoading: false,
            formData: {
                workType: 1,
                workName: "",
                workUrl: "",
                linkId: "",
                linkDescription: "",
                numberType: "",
                startTime: "",
                endTime: "",
                workOrderTotal: "",
                lowerProportion: "",
                workAccount: "",
                workPassword: "",
                autoCloseEnabled: false,
            },
            numberTypeList: [
                // 1：WhatsApp，2：Telegram，3：Line，4：自定义
                {
                    label: "WhatsApp",
                    value: 1,
                },
                {
                    label: "Telegram",
                    value: 2,
                },
                {
                    label: "Line",
                    value: 3,
                },
                {
                    label: "自定义",
                    value: 4,
                },
            ],
            workTypeList: [
                {
                    label: "云控",
                    value: 1,
                },
                {
                    label: "非自动化",
                    value: 2,
                },
            ],
        };
    },
    methods: {
        validateUrl(rule, value, callback) {
            const reg =
                /^(https?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(:(\d{1,5}))?(\/[^\s]*)?$/i;
            console.log(
                value.match(reg),
                value,
                "value.match(reg)value.match(reg)"
            );
            if (value.match(reg)) {
                callback();
            } else {
                callback(new Error("请输入正确的URL"));
            }
        },

        /** 打开弹窗 */
        async open(row) {
            this.dialogVisible = true;
            this.formData.workType = 1;
            this.formData.autoCloseEnabled = true;
            // 修改时，设置数据
            if (row.id) {
                this.dialogTitle = "修改工单";

                this.formData = {
                    ...this.formData,
                    ...row,
                    autoCloseEnabled: row.autoCloseEnabled ? true : false,
                };
                Object.keys(row).forEach((key) => {
                    const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?/;
                    if (row[key] && isoRegex.test(row[key])) {
                        this.formData[key] = new Date(row[key]);
                    }
                });
            } else {
                this.dialogTitle = "新增工单";
            }
        },

        /** 提交按钮 */
        async submitForm() {
            // 校验主表
            await this.$refs["formRef"].validate();
            this.formLoading = true;
            try {
                const data = this.formData;
                data.autoCloseEnabled = Number(data.autoCloseEnabled);
                // 修改的提交
                if (data.id) {
                    await editWorkOrder(data);
                    this.$modal.msgSuccess("修改成功");
                    this.dialogVisible = false;
                    this.$emit("success");
                    return;
                }
                // 添加的提交
                await addWorkOrder(data);
                this.$modal.msgSuccess("新增成功");
                this.dialogVisible = false;
                this.$emit("success");
            } finally {
                this.formLoading = false;
            }
        },

        /** 表单重置 */
        reset() {
            this.formData = {
                workType: "",
                workName: "",
                linkId: "",
                workUrl: "",
                linkDescription: "",
                numberType: "",
                startTime: "",
                endTime: "",
                workOrderTotal: "",
                lowerProportion: "",
                workAccount: "",
                workPassword: "",
            };
            this.resetForm("formRef");
        },
        handleClose() {
            this.reset();
        },
    },
    created() {},
};
</script>
